package com.idanchuang.support.mybatis.crypt.resolver;

import com.idanchuang.support.mybatis.crypt.handler.CryptHandler;
import com.idanchuang.support.mybatis.crypt.handler.CryptHandlerFactory;
import org.apache.ibatis.binding.MapperMethod;

import java.util.Map;

/**
 * 简单加密处理者
 *
 * @author kamjin1996
 */
public class SimpleMethodEncryptResolver implements MethodEncryptResolver {

    private MethodAnnotationEncryptParameter encryptParameter;

    public SimpleMethodEncryptResolver() {
    }

    public SimpleMethodEncryptResolver(MethodAnnotationEncryptParameter encryptParameter) {
        this.encryptParameter = encryptParameter;
    }

    @Override
    public Object processEncrypt(Object param) {
        if (param instanceof MapperMethod.ParamMap) {
            Map newMap = new MapperMethod.ParamMap<>();
            newMap.putAll((Map) param);
            Object originValue;
            if (newMap.containsKey("param1")) {
                originValue = newMap.get("param1");
            } else if (newMap.containsKey("et")) {
                originValue = newMap.get("et");
            } else {
                return param;
            }
            if (originValue == null) {
                return param;
            }
            CryptHandler cryptHandler = CryptHandlerFactory.getCryptHandler(originValue, encryptParameter.getCryptField());
            Object encryptValue = cryptHandler.encrypt(originValue, encryptParameter.getCryptField());
            if (originValue == encryptValue) {
                return param;
            }
            for (Object key : newMap.keySet()) {
                if (originValue == newMap.get(key)) {
                    newMap.put(key, encryptValue);
                }
            }
            return newMap;
        }
        return CryptHandlerFactory.getCryptHandler(param, encryptParameter.getCryptField())
                .encrypt(param, encryptParameter.getCryptField());
    }
}
